package cn.wmingming.e3mall.manager.controller;

import cn.wmingming.common.utils.FastDFSClient;
import cn.wmingming.common.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;


/**
 * 图片上传控制器
 */
@Controller
public class PictureController {

    @Value("${IMAGE_SERVER_URL}")
    private String IMAGE_SERVER_URL;

    @RequestMapping(value = "/pic/upload",produces = MediaType.TEXT_PLAIN_VALUE +";chartset=utf-8")
    @ResponseBody
    public String fileUpload(MultipartFile uploadFile){
        try {
            //1、取文件的扩展名
            String originalFileName = uploadFile.getOriginalFilename();
            String extName = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
            //创建一个fastDFS客户端
            FastDFSClient fastDFSClient = new FastDFSClient("classpath:conf/fastDFSClient.conf");
            //执行文件上传
            String path = fastDFSClient.uploadFile(uploadFile.getBytes(), extName);
            //拼接url
            String url = IMAGE_SERVER_URL+path;
            //组装Map
            Map map = new HashMap();
            map.put("error",0);
            map.put("url",url);
            return JsonUtils.objectToJson(map);

        } catch (Exception e) {
            e.printStackTrace();
            //组装Map
            Map map = new HashMap();
            map.put("error",1);
            map.put("message","图片上传失败");
            return JsonUtils.objectToJson(map);
        }
    }
}
